package com.yitiao.socket.chatroom.bio;

import com.yitiao.socket.chatroom.CommonConst;
import com.yitiao.socket.chatroom.MyClient;
import lombok.SneakyThrows;

import java.io.*;
import java.net.Socket;

public class ChatClient extends MyClient {



    public ChatClient(Socket client) {
        this.client = client;
    }

    @SneakyThrows
    public void start() {
        new Thread(new ClientInputHandler(this)).start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
        while (!isQuit) {
            String line = reader.readLine();
            if (line != null) {
                System.out.println(line);
            }
        }
    }

    @SneakyThrows
    public void send(String line) {
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
        writer.write(line);
        writer.flush();
    }

    @SneakyThrows
    public void close() {
        this.isQuit = true;
        client.close();
    }

    @SneakyThrows
    public static void main(String[] args) {

        Socket socket = new Socket(CommonConst.HOST, CommonConst.PORT);
        ChatClient client = new ChatClient(socket);
        client.start();
    }
}
